package com.wavehi.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Author WaveHi
 * @Date 2/9/2021 下午 2:43
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description 使用数据库连接池
 */
public class JDBCUtilsUp {
    private JDBCUtilsUp() {
    }

    private static DataSource ds;//数据库连接池
    private static ThreadLocal<Connection> conns = new ThreadLocal<>();

    static {
        //获取属性集
        Properties properties = new Properties();
        //获取配置文件输入流
        InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
        //将输入流加载到属性集
        try {
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取数据库连接池
        try {
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() {
        Connection conn = conns.get();
        try {
            conn = ds.getConnection();
            conn.setAutoCommit(false);
            conns.set(conn);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            return conn;
        }
    }

    /**
     * 回滚事务
     */
    public static void rollbackAndClose() {
        Connection conn = conns.get();
        try {
            if(conn != null) {
                conn.rollback();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                if(conn != null) {
                    conn.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        conns.remove();
    }

    /**
     * 提交事务并断开数据库连接
     */
    public static void commitAndClose() {
        Connection conn = conns.get();
        try {
            if(conn != null) {
                conn.commit();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        conns.remove();
    }

}
